//
//  AppDelegate.m
//  KaiChat
//
//  Created by lx on 2023/10/16.
//

#import "AppDelegate.h"
#import "HJStartPageController.h"
#import "HJNavigationController.h"
#import "HJMainController.h"
#import "HJLoginController.h"
#import "HJVersionUpdate.h"
#import "HJMessageImageDto.h"
#import "HJNetworkReachabilityManager.h"
#import "HJMessageFileManager.h"
#import "HJChatMessageModel.h"
#import "LSSafeProtector.h"
#import "HJMinePresent.h"
#import "HJWebSocketManager.h"
#import "HJAlertController.h"
#import "HJLaunchScreenController.h"
#import "HJIM.h"
#import "HJFlutterManager.h"
#import <AppsFlyerLib/AppsFlyerLib.h>
#import "HJChatGroupModel.h"
#import "HJGroupSettingController.h"
#import "HJNavigationController.h"
#import "HJChatController.h"
#import "HJInformationPresent.h"
#import "ZFLandscapeRotationManager.h"
#import <OneSignalFramework/OneSignalFramework.h>
#import <OneSignalExtension/OneSignalExtension.h>
#import <OneSignalNotifications/OneSignalNotifications.h>
#import "HJFlutterController.h"
#import <Bugly/Bugly.h>
#import "HJAWSS3Manager.h"

@interface AppDelegate ()<OSNotificationPermissionObserver, UNUserNotificationCenterDelegate>



@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self crashHandle];
    [self setAppsFlyer];
    [self pushSettingWithOptions:launchOptions];
    [[HJNetworkReachabilityManager shareManager] monitorNetworkStatus];
    [self doInit];
    [HJLaunchScreenController show];
    [self settingKeyboardManager];
    [self registeredNotification];
    [self imageLoadingSettings];
    [self setAppLanguages];
    
    
//        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"81286110717c31e5dc7632f35fad11f1.mp4" ofType:nil];
//
//        NSData *fileData = [NSData dataWithContentsOfFile:filePath];
//        NSString *dataString = [[NSDate date] stringWithFormat:@"yyMMddHHmmss"];
//
//         NSString *objectKey = [NSString stringWithFormat:@"hj-global/bit-chat/%ld/%@/1/%@", HJFileTypeOther, dataString, filePath.lastPathComponent];
//
//    [HJAWSS3Manager.shareS3Manager updateWithData:fileData objectKey:objectKey progressBlock:^(int64_t totalBytesSent, int64_t completeBytes) {
//        
//        NSLog(@"totalBytesSent = %ld, completeBytes = %ld", totalBytesSent, completeBytes);
//        
//        
//    } completionHandler:^(NSString * _Nullable url, NSError * _Nullable error) {
//        NSLog(@"error = %@, url = %@", error, url);
//        
//    }];
//    
    
    
//    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
//
//    [HJAWSS3Manager.shareS3Manager downloadWithObjectKey:@"hj-global/bit-chat/5/240416093415/1/KaiChat1.ipa" toLocalPath:@"KaiChat1.ipa".tj_downloadCachePath progressBlock:^(int64_t totalBytesWritten, int64_t bytesWritten) {
//                NSLog(@"totalUnitCount = %lld, totalBytesWritten = %lld", bytesWritten, totalBytesWritten);
//        } completionHandler:^(NSError * _Nullable error) {
//                        NSLog(@"error = %@", error);
//        }];
//  
 
    return YES;
}

- (void)pushSettingWithOptions:(NSDictionary *)launchOptions {
    UNUserNotificationCenter.currentNotificationCenter.delegate = self;
    [OneSignal.Debug setLogLevel:ONE_S_LL_NONE];
    [OneSignal initialize:getOneSignalAppId() withLaunchOptions:launchOptions];
    [OneSignal.Notifications requestPermission:^(BOOL accepted) {
        NSLog(@"User accepted notifications: %d", accepted);
    } fallbackToSettings:true];
    [OneSignal.Notifications addPermissionObserver:self];
}

- (void)setAppsFlyer {
    [[AppsFlyerLib shared] setAppsFlyerDevKey:getAppsFlyerKey()];
    [[AppsFlyerLib shared] setAppleAppID:getAppId()];
    [AppsFlyerLib shared].isDebug = NO;
}

- (void)setAppLanguages {
    //    id obje = [[NSUserDefaults standardUserDefaults] valueForKey:@"AppleLanguages"];
    //    NSLog(@"obje = %@", obje);
    //    [[NSUserDefaults standardUserDefaults] setObject:@[@"en-CN"] forKey:@"AppleLanguages"];
    //    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)doInit {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    [self.window makeKeyAndVisible];
    [self gotoMainController];
}

- (void)imageLoadingSettings {
    [SDImageCache sharedImageCache].config.maxDiskAge = 3600 * 24 * 30;
    [SDImageCache sharedImageCache].config.maxMemoryCount = 1024 * 1024 * 80;
    [SDImageCache sharedImageCache].config.shouldUseWeakMemoryCache = YES;
}

- (void)gotoMainController {
    if (HJUserInfo.isLogin) {
        self.window.rootViewController =  [[HJMainController alloc] init];
        [HJMinePresent refreshTokenComplete:^(NSError * _Nullable error) {
            if (!error) {
                [OneSignal login:HJUserInfo.userId];
                [HJWebSocketManager.shareManager connect];
                [self loadData];
                [HJFlutterManager.sharedManager preloadWalletEngine];
            }
        }];
    } else {
        self.window.rootViewController = [[HJNavigationController alloc] initWithRootViewController:[[HJStartPageController alloc] init]];
    }
    [self checkVersionUpdate];
}

- (void)loginSucceed {
    self.window.rootViewController =  [[HJMainController alloc] init];
    [HJWebSocketManager.shareManager connect];
    [HJIM.shareIM.conversationManager updateOfficialConversation];
    [HJFlutterManager.sharedManager preloadWalletEngine];
    [OneSignal login:HJUserInfo.userId];
    [OneSignal.User addTagWithKey:@"kai_uid" value:HJUserInfo.userId];
    [self loadData];
    
    if (self.openUrl) {
        [self openURL:self.openUrl];
    }
}

- (void)logOut {
    [OneSignal.User removeTag:@"kai_uid"];
    [OneSignal logout];
    [HJWebSocketManager.shareManager disconnect];
    [[SDImageCache sharedImageCache] clearMemory];
    [HJUserInfo clear];
    UIApplication.sharedApplication.applicationIconBadgeNumber = 0;
    self.window.rootViewController = [[HJNavigationController alloc] initWithRootViewController:[[HJStartPageController alloc] init]];
}


/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    ZFInterfaceOrientationMask orientationMask = [ZFLandscapeRotationManager supportedInterfaceOrientationsForWindow:window];
    if (orientationMask != ZFInterfaceOrientationMaskUnknow) {
        return (UIInterfaceOrientationMask)orientationMask;
    }
    /// 这里是非播放器VC支持的方向
    return UIInterfaceOrientationMaskPortrait;
}

- (void)gotoLoginController {
    self.window.rootViewController = [[HJNavigationController alloc] initWithRootViewController:[[HJStartPageController alloc] init]];
}

- (void)registeredNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOut) name:tokenErrorNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logOut) name:logoutNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSucceed) name:loginSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoLoginController) name:registerSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoLoginController) name:cancellationSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLaunchScreenVideoFinishNotification) name:launchScreenVideoFinishNotification object:nil];
}

- (void)handleLaunchScreenVideoFinishNotification {
    [self readPasteboard];
}

- (void)settingKeyboardManager {
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 20;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].previousNextDisplayMode = IQPreviousNextDisplayModeAlwaysHide;
    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = NO;
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)loadData {
    [HJMinePresent loadUserInfoComplete:nil];
    [HJInformationPresent loadModuleListDataComplete:^(NSArray * _Nullable datas) {}];
}

- (void)IpCheck {
    //    [HJMinePresent loginCheckComplete:^(BOOL res, NSString * _Nonnull msg) {
    //        if (res) {
    //            return;
    //        };
    //
    //        [HJAlertController alertInController:getMainController() title:nil message:isEmptyString(msg) ? @"Due to policy restrictions,we are temporarily unable to support your current region" : msg left:nil right:^(HJAlertAction * _Nonnull action) {
    //            action.title = @"OK";
    //            action.titleColor = UIColor.tj_mainColor;
    //            [action setHandler:^{
    //                [[NSNotificationCenter defaultCenter] postNotificationName:logoutNotification object:nil];
    //            }];
    //        }];
    //    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [self checkVersionUpdate];
    if (HJUserInfo.isLogin) {
        [HJIM.shareIM.conversationManager updateBadge];
        [HJMinePresent refreshTokenComplete:^(NSError * _Nullable error) {
            if (!error) {
                [HJWebSocketManager.shareManager reconnect];
                [HJMinePresent loadUserInfoComplete:nil];
                [HJInformationPresent loadModuleListDataComplete:^(NSArray * _Nullable datas) {}];
            }
        }];
    }
}

- (void)readPasteboard {
    if ([self.openUrl.absoluteString hasPrefix:@"itms-"]) {
        NSString *content = [UIPasteboard generalPasteboard].string;
        if (isEmptyString(content) && ![content containsString:@"kai://"]) {
            return;
        }
        [(AppDelegate *)UIApplication.sharedApplication.delegate openURL:content.URL];
        self.openUrl = nil;
        [UIPasteboard generalPasteboard].string = @"";
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [HJWebSocketManager.shareManager disconnect];
}

- (void)applicationDidEnterBackgroundTest {
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    messageModel.chatType = HJChatTypeGroup;
    messageModel.groupId = @"84";
    messageModel.messageType = HJMessageTypeText;
    messageModel.sessionId = messageModel.groupId;
    messageModel.content = @"推到后台发送通知";
    [HJIM.shareIM.chatManager sendMessageWithModel:messageModel begin:nil completion:nil];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (HJUserInfo.isLogin && !isEmptyString(HJUserInfo.userId)) {
        [AppsFlyerLib shared].customerUserID = HJUserInfo.userId;
    }
    [[AppsFlyerLib shared] start];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    self.openUrl = url;
    [self openURL:url];
    return YES;
}

- (void)openURL:(NSURL *)url {
    [self openURL:url popBlock:nil];
}

- (void)openURL:(NSURL *)url popBlock:(void (^__nullable)(void))popBlock {
    if ([url.scheme isEqualToString:@"kai"]) {//shareExtension
        NSDictionary *queryDict = [HJTools parseQueryForURL:url];
        NSLog(@"queryDict = %@", queryDict);
        if ([queryDict[@"type"] isEqualToString:@"register"]) {
            HJTools.tool.inviteUserId = queryDict[@"userId"];
            NSLog(@"HJTools.tool.inviteUserId = %@", HJTools.tool.inviteUserId);
            return;
        }
        
        if (!HJUserInfo.isLogin) {
            return;
        }
        
        NSString *groupId = queryDict[@"groupId"];
        self.openUrl = nil;
        if (!isEmptyString(groupId)) {
            [HJIM.shareIM.groupManager loadPublicGroupInfoByGroupId:groupId completion:^(HJChatGroupModel * _Nullable groupModel, NSError * _Nullable error) {
                if (([error.domain isEqualToString:ERRPRDOMAIN] && (error.code == groupNotExistCode || error.code == groupDisbandCode)) || groupModel.status.intValue == 2) {
                    [HJAlertController alertInController:getMainController() title:nil message:@"Group does not exist" left:nil right:^(HJAlertAction * _Nonnull action) {
                        action.title = @"OK";
                        action.titleColor = UIColor.tj_mainColor;
                    }];
                    return;
                }
                
                if (groupModel) {
                    
                    UIViewController *currentViewController = HJTools.currentViewController;
                    
                    BOOL isContainChatController = NO;
                    BOOL isContainGroupSettingController = NO;
                    
                    for (UIViewController *obj in currentViewController.navigationController.viewControllers) {
                        if ([obj isKindOfClass:HJGroupSettingController.class]) {
                            isContainGroupSettingController = YES;
                        }
                        if ([obj isKindOfClass:HJChatController.class]) {
                            isContainChatController = YES;
                        }
                    }
                    
                    if (isContainChatController && isContainGroupSettingController) {
                        [currentViewController.navigationController popToRootViewControllerAnimated:NO];
                    } else {
                        HJGroupSettingController *topViewController = (HJGroupSettingController *)currentViewController.navigationController.topViewController;
                        if ([topViewController isKindOfClass:HJGroupSettingController.class] && topViewController.isShareOpen) {
                            currentViewController.navigationController.viewControllers = [currentViewController removeNavChildViewControllers:@[@"HJGroupSettingController"]];
                        }
                    }
                    
                    HJGroupSettingController *groupSettingController = [[HJGroupSettingController alloc] init];
                    groupSettingController.groupModel = groupModel;
                    groupSettingController.isShareOpen = YES;
                    groupSettingController.popBlock  = popBlock;
                    if (currentViewController.navigationController) {
                        [currentViewController.navigationController pushViewController:groupSettingController];
                    } else {
                        [[HJTools currentNavController] pushViewController:groupSettingController];
                    }
                }
            }];
        }
    }
}


- (void)checkVersionUpdate {
    //    NSInteger showUpdateDate = HJUserInfo.showUpdateDate.integerValue;
    //    if (showUpdateDate > 0) {
    //        NSCalendar *calendar = [NSCalendar currentCalendar];
    //        NSDateComponents *lastComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate dateWithTimeIntervalSince1970:showUpdateDate]];
    //        NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
    //        if (lastComponents.year == components.year && lastComponents.month == components.month && lastComponents.day == components.day) {
    //            TJLog(@"当天已检查更新不再显示更新");
    //            return;
    //        }
    //    }
    
    [HJVersionUpdate checkVersionUpdateInController:[HJTools currentViewController]];
}


- (void)onNotificationPermissionDidChange:(BOOL)permission {
    
}


- (void)crashHandle {
    [Bugly startWithAppId:getBuglyAppId()];
    
#ifdef DEBUG
    
#else
    [LSSafeProtector openSafeProtector];
#endif
    
}

- (void)dealloc {
    [OneSignal.Notifications removePermissionObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    
    TJLog(@"didReceiveNotificationResponse %@", response.notification.request.content.userInfo);
    
    NSDictionary *custom = response.notification.request.content.userInfo[@"custom"][@"a"];
    NSDictionary *message = [custom[@"message"] mj_JSONObject];
    
    NSInteger type = 0;
    if ([message.allKeys containsObject:@"type"]) {
        type = [message[@"type"] intValue];
    } else if ([message.allKeys containsObject:@"typ"]) {
        type = [message[@"typ"] intValue];
    }
    
    if (type == 10) {
        
        NSMutableDictionary *arguments = [NSMutableDictionary dictionary];
        [arguments setValue:message forKey:@"transaction"];
        
        UIViewController *currentViewController = [HJTools currentViewController];
        if ([currentViewController isKindOfClass:HJFlutterController.class]) {
            HJFlutterController *flutterController = (HJFlutterController *)currentViewController;
            [flutterController invokeWithName:HJFlutterPageWallet arguments:arguments];
            return;
        }
        
        HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageWallet];
        flutterController.arguments = arguments;
        [[HJTools currentNavController] pushViewController:flutterController];
        return;
    }
    
    NSString *title = response.notification.request.content.title;
    NSString *senderId = toString(message[@"user_id"]);
    NSString *sessionId = toString(message[@"session_id"]);
    
    NSInteger chat_type = [message[@"chat_type"] intValue];
    HJChatType chatType = HJChatTypeOfficial;
    if (chat_type == 1) {
        chatType = HJChatTypeSingle;
    } else if (chat_type == 2) {
        chatType = HJChatTypeGroup;
    } else {
        return;
    }
    
    HJChatSystemMsgType systemMsgType = [message[@"sys_msg_type"] intValue];
    if (chatType == HJChatTypeSingle && systemMsgType == HJChatSystemMsgTypeApplyFridend) {
        [[HJTools currentNavController] pushViewControllerWithName:@"HJApplyListController"];
        return;
    }
    
    HJChatSessionModel *sessionModel = [HJChatSessionModel sessionModelWithSessionId:sessionId sessionUserd:senderId chatType:chatType sessionName:title];
    [HJChatController showWithSessionModel:sessionModel];
    completionHandler();
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"didReceiveRemoteNotification.userInfo = %@", userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"----Appdelegatewillpresentdelegate");
    completionHandler(UNNotificationPresentationOptionBadge);
}

- (void)applicationWillTerminate:(UIApplication *)application {
    NSLog(@"applicationWillTerminate");
    [HJWebSocketManager.shareManager disconnect];
}


@end
